$(function () {
  function initScrollCarousel (options) {
    const {
      wrapperSelector,
      itemSelector,
      prevButtonSelector,
      nextButtonSelector,
      gap = 20,
      throttleWait = 500
    } = options;

    const wrapper = document.querySelector(wrapperSelector);
    const productItem = document.querySelector(itemSelector);
    if (!wrapper || !productItem) return;

    const scrollStep =
      parseInt(productItem.getBoundingClientRect().width) + gap;

    // 节流函数
    function throttle (func, wait = 500) {
      let context, args;
      let previous = 0;
      return function () {
        let now = +new Date();
        context = this;
        args = arguments;
        if (now - previous > wait) {
          func.apply(context, args);
          previous = now;
        }
      };
    }

    // 滑动逻辑
    let scrollLeft = throttle(() => {
      const currentScrollLeft = wrapper.scrollLeft;
      if (currentScrollLeft > 0) {
        $(wrapper).animate(
          { scrollLeft: currentScrollLeft - scrollStep },
          'slow'
        );
      }
    }, throttleWait);

    let scrollRight = throttle(() => {
      const currentScrollLeft = wrapper.scrollLeft;
      const maxScrollLeft = wrapper.scrollWidth - wrapper.clientWidth;
      if (currentScrollLeft < maxScrollLeft) {
        $(wrapper).animate(
          { scrollLeft: currentScrollLeft + scrollStep },
          'slow'
        );
      }
    }, throttleWait);

    // 获取按钮并绑定点击事件
    const buttonLeft = document.querySelector(prevButtonSelector);
    const buttonRight = document.querySelector(nextButtonSelector);

    if (buttonLeft) {
      $(buttonLeft).on('click', scrollLeft);
    }
    if (buttonRight) {
      $(buttonRight).on('click', scrollRight);
    }

    // 监听滚动事件更新按钮状态
    wrapper.addEventListener('scroll', function () {
      const maxScrollLeft = wrapper.scrollWidth - wrapper.clientWidth;
      const currentScrollLeft = wrapper.scrollLeft;

      if (buttonRight) {
        if (currentScrollLeft >= maxScrollLeft) {
          buttonRight.disabled = true;
          buttonRight.classList.remove('slide-button-active');
        } else {
          buttonRight.disabled = false;
          buttonRight.classList.add('slide-button-active');
        }
      }

      if (buttonLeft) {
        if (currentScrollLeft === 0) {
          buttonLeft.disabled = true;
          buttonLeft.classList.remove('slide-button-active');
        } else {
          buttonLeft.disabled = false;
          buttonLeft.classList.add('slide-button-active');
        }
      }
    });

    // 初始化时手动触发一次滚动检查
    wrapper.dispatchEvent(new Event('scroll'));
  }
  function initSpreadOut () {
    // 给外层容器绑定事件，委托到 svg
    $(document).on(
      'click',
      '.about-rt-info-text .description-title',
      function () {
        const $title = $(this); // 当前点击的标题
        const $li = $title.closest('li'); // 当前 li
        const $content = $li.find('p'); // 当前 li 下的内容
        const $arrow = $title.find('svg'); // 当前标题里的箭头
        $content.slideToggle(200); // 只展开/收起当前 p
        $arrow.toggleClass('rotate'); // 只转当前箭头
      }
    );
  }

  // 定义映射关系
  const dropdownMap = {
    '#countryList': DropdownOptions.CountryListSelect || []
  };

  // 渲染函数
  function renderOptions ($ul, options) {
    $ul.empty();
    options.forEach(opt => {
      $ul.append(`<li data-value="${opt.value}">${opt.label}</li>`);
    });
  }

  // 批量渲染
  Object.entries(dropdownMap).forEach(([selector, options]) => {
    renderOptions($(selector), options);
  });

  // 打开/关闭当前下拉（并关闭其它）
  $('.select-dropdown').on('click', function (e) {
    e.stopPropagation();
    $('.select-dropdown').not(this).removeClass('open');
    $(this).toggleClass('open');
  });
  $(document).on('click', () => $('.select-dropdown').removeClass('open'));
  $('.select-dropdown').click(function () {
    var dropdown = $(this);
    var ul = dropdown.children('ul');
    var p = dropdown.find('p');
    var input = dropdown.find('input');
    // 如果为二级下拉
    if (ul.find('ul li').length) {
      var li = ul.find('ul li');
    } else {
      // 一级
      var li = ul.find('li');
    }

    var arrows = dropdown.find('.select-arrows');
    if (ul.css('display') == 'none') {
      ul.slideDown('fast');
      arrows.css('transform', 'rotate(180deg)');
    } else {
      ul.slideUp('fast');
      arrows.css('transform', 'rotate(0)');
    }

    li.click(function () {
      var txt = $(this).text();
      var firstSelect = $(this).parent().prev().text();
      p.html(`${firstSelect} ${txt}`);
      input.val(`${firstSelect} ${txt}`);
      ul.slideUp('fast');
      arrows.css('transform', 'rotate(0)');
      // 如果选中的是 'Other'，则将 select-dropdown 的宽度设置为 50%
    });
    dropdown.mouseleave(function () {
      ul.slideUp('fast');
      arrows.css('transform', 'rotate(0)');
    });
  });
  // 点击其他地方关闭下拉
  $(document).click(function () {
    $('.select-dropdown').removeClass('open');
  });

  // 校验字段
  const validationRules = [
    {
      key: 'consultingName',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter your name',
        maxLength: 'The length cannot exceed 50'
      }
    },
    {
      key: 'companyName',
      required: true,
      maxLength: 50,
      errorMessage: {
        required: 'Please enter companyName'
      }
    },
    {
      key: 'email',
      required: true,
      maxLength: 30,
      regex: regEmail,
      errorMessage: {
        required: 'Please enter your email',
        maxLength: 'The length cannot exceed 30',
        regex: 'Please enter a valid email'
      }
    },
    {
      key: 'country',
      required: true,
      errorMessage: {
        required: 'Please Select your Country'
      }
    },
    {
      key: 'PhoneNumber',
      required: true,
      regex: regPhone,
      errorMessage: {
        required: 'Please enter your Phone',
        regex: 'Please enter a valid phone number'
      }
    },
    {
      key: 'checkbox',
      required: false
    },
    {
      key: 'message',
      required: true,
      maxLength: 200,
      errorMessage: {
        required: 'Please Select your Message',
        maxLength: 'The length cannot exceed 200'
      }
    }
  ];

  // 通用校验函数
  function validateField (rule, $context) {
    let $input;
    let $error;
    let value = '';

    // ⭐ 特殊处理评分控件
    if (rule.type === 'custom' && rule.key === 'rating') {
      $input = $context.find('.star-rating'); // 直接找容器
      $error = $input.closest('.form-item').find('.error-message');
      value = $input.find('.star.selected').length || 0;

      if (rule.required && !value) {
        $error.text(rule.errorMessage.required).addClass('show');
        return false;
      }
      $error.removeClass('show');
      return true;
    }

    // 📌 默认处理 input/textarea/select
    $input = $context.find(`#${rule.key}`);
    $error = $input.closest('.form-item').find('.error-message');

    if ($input.attr('type') === 'checkbox') {
      value = $input.prop('checked'); // true/false
    } else {
      const rawVal = $input.val();
      value = typeof rawVal === 'string' ? rawVal.trim() : '';
    }

    // 必填校验
    if (rule.required && !value) {
      $error.text(rule.errorMessage.required).addClass('show');
      return false;
    }

    // 最大长度校验
    if (rule?.maxLength && value.length > rule.maxLength) {
      $error.text(rule.errorMessage.maxLength).addClass('show');
      return false;
    }

    // 正则校验
    if (rule?.regex && value && !rule?.regex.test(value)) {
      $error.text(rule.errorMessage.regex).addClass('show');
      return false;
    }

    // 校验通过
    $error.removeClass('show');
    return true;
  }

  function getFormValues (leaveRulesData, $context) {
    let allValid = true;
    const formValues = {};

    leaveRulesData.forEach(rule => {
      let value = '';

      // 特殊处理自定义组件
      if (rule.type === 'custom' && rule.key === 'rating') {
        value = $context.find('.star-rating .star.selected').length || 0;
        formValues[rule.key] = value;
        return; // 继续下一个rule
      }

      // 查找表单元素
      const $elements = $context
        .find(`[name="${rule.key}"]`)
        .filter('input, textarea, select');

      if ($elements.length === 0) {
        formValues[rule.key] = '';
        return;
      }

      // 根据元素类型处理值
      const firstElement = $elements[0];
      const tagName = firstElement.tagName.toLowerCase();
      const type = (firstElement.type || '').toLowerCase();

      switch (tagName) {
        case 'input':
          if (type === 'checkbox') {
            value = handleCheckboxes($elements, rule.key, $context);
          } else if (type === 'radio') {
            value =
              $context.find(`input[name="${rule.key}"]:checked`).val() || '';
          } else {
            value = ($elements.val() || '').trim();
          }
          break;
        case 'textarea':
          value = ($elements.val() || '').trim();
          break;
        case 'select':
          value = $elements.val();
          break;
      }

      formValues[rule.key] = value;

      // 校验逻辑
      if (rule.required || rule.regex) {
        if (!validateField(rule, $context)) {
          allValid = false;
        }
      }
    });

    return allValid ? formValues : null;
  }

  // 单独处理checkbox逻辑
  function handleCheckboxes ($elements) {
    if ($elements.length > 1) {
      // 多个checkbox
      return $elements
        .filter(':checked')
        .map(function () {
          return $(this).val();
        })
        .get();
    } else {
      // 单个checkbox
      return $elements.is(':checked');
    }
  }

  // 联系客服提交按钮
  $('.dm-dialog-btn').click(function () {
    const $fileContent = $('.form-content');
    const formValues = getFormValues(validationRules, $fileContent);
    console.log('提交表单', formValues);
    if (!formValues) return;
  });

  // 联系我们点击按钮
  $('.contact-us-button').click(function () {
    $('.contact-dialog').fadeIn();
  });

  // 关闭弹框按钮
  $('.dm-header-close-btn').click(function () {
    $('.contact-dialog').fadeOut();
    // 清空表单
    $('.refDialogWrite')[0].reset();
    // 手动重置自定义下拉菜单
    $('.refDialogWrite .select-dropdown').each(function () {
      const $dropdown = $(this);
      $dropdown.find('p').text(''); // 清空显示文本
      $dropdown.find('input[type="hidden"]').val(''); // 清空隐藏输入框
      $dropdown.find('.error-message').text(''); // 清空错误信息
    });
    // 清空校验错误提示
    $('.error-message').removeClass('show');
  });

  initSpreadOut();
  initScrollCarousel({
    wrapperSelector: '.popular-designs-content .cards-wrapper',
    itemSelector: '.product-card-item',
    prevButtonSelector: '.popular-designs-content .button-prev',
    nextButtonSelector: '.popular-designs-content .button-next',
    gap: 20, // 卡片之间的间距
    throttleWait: 500 // 节流时间
  });
  initScrollCarousel({
    wrapperSelector: '.popular-designs-content-guide .cards-wrapper',
    itemSelector: '.popular-designs-content-guide .product-card-item',
    prevButtonSelector: '.popular-designs-content-guide .button-prev',
    nextButtonSelector: '.popular-designs-content-guide .button-next',
    gap: 20, // 卡片之间的间距
    throttleWait: 500 // 节流时间
  });
});
